package com.ar4j.type;

import java.sql.Types;

/**
 * Converter class providing conversion between Boolean and a string with a single character ("Y"/"N") in the backing store
 */
public class SingleCharacterStringBooleanTypeConverter implements ITypeConverter<Boolean, String> {

  @Override
  public String convertToStorage(Boolean value) {
    String out = null;
    if(value != null) {
      out = (value ? "Y" : "N");
    }
    return out;
  }

  @Override
  public Boolean convertFromStorage(String storageValue) {
    Boolean out = null;
    if (storageValue != null) {
      // char(1) type in MySql returns a String in JDBC and not a Character
      if ("Y".equals(storageValue)) {
        out = Boolean.TRUE;
      } else if ("N".equals(storageValue)) {
        out = Boolean.FALSE;
      } else {
        throw new IllegalArgumentException("Unsupported convertion from of single char boolean of value: " + storageValue);
      }
    }

    return out;
  }
  
  @Override
  public Class<Boolean> getObjectType() {
    return Boolean.class;
  }

  @Override
  public Class<String> getStorageType() {
    return String.class;
  }

  @Override
  public int getSqlType() {
    return Types.CHAR;
  }

  @Override
  public void setTypes(Class<Boolean> objectType, Class<String> storageType) {
    throw new UnsupportedOperationException(("Cannot execute setTypes on DateWithoutMillisTypeConverter, it is not needed"));    
  }

}
